package com.dididoctor.doctor.Ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;

import com.dididoctor.doctor.R;


/**
 * Created by zhangqiang on 15/4/3.
 */
public class ZoomImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener {

    private boolean mOnce;

    /**
     * 初始化时的缩放值
     */
    private float mInitScale;

    /**
     * 放大的最大值
     */
    private float mMaxScale;
    /**
     * 双击放大到达的值
     */
    private float mMidScale;

    private Matrix mScaleMatrix;

    private ScaleGestureDetector mScaleGestureDetector;

    //-------多点触控
    /**
     * 记录上次多点触控的数量
     */
    private int mLastPointerCount = 0;
    private float mLastX;
    private float mLastY;

    private int mTouchSlop = 0;
    private boolean isCanDrag = false;


    private boolean isCheckLeftAndRight;
    private boolean isCheckTopAndBottom;
    private Matrix matrix;

    //双击放大与缩小
    private GestureDetector gestureDetector = null;
    private boolean isAutoScale = false;

    private Bitmap bitmap;

    public ZoomImageView(Context context) {
        this(context, null);
    }

    public ZoomImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public void reset() {
        mOnce = false;

        requestLayout();
    }


    public ZoomImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        DisplayMetrics dm = new DisplayMetrics();

        this.mScaleMatrix = new Matrix();


        setScaleType(ScaleType.MATRIX);

        this.mScaleGestureDetector = new ScaleGestureDetector(context, this);
        setOnTouchListener(this);

        this.mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

        this.gestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onDoubleTap(MotionEvent event) {

                if (isAutoScale) {
                    return true;
                }
                float x = event.getX();
                float y = event.getY();
                if (getScale() < mMidScale) {

                    postDelayed(new AutoScaleRunnable(mMidScale, x, y), 16);
                    isAutoScale = true;
                } else {

                    postDelayed(new AutoScaleRunnable(mInitScale, x, y), 16);
                    isAutoScale = true;
                }
                return true;
            }
        });
    }


    @Override
    protected void onDraw(Canvas canvas) {
        canvas.drawColor(getResources().getColor(R.color.black));
        super.onDraw(canvas);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //得到控件的宽和高
        initZoom();
    }

    public void initZoom() {
        int width = getWidth();
        int height = getHeight();

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        int drawableWidth = drawable.getIntrinsicWidth();
        int drawableHeight = drawable.getIntrinsicHeight();

        float scale = 1.0f;
        /**
         * 如果图片的宽度大于控件的宽度，但是高度小于控件的高度，缩小
         */
        if (drawableWidth > width && drawableHeight < height) {
            scale = width * 1.0f / drawableWidth;
        }
        /**
         * 如果图片的高度大于控件的高度，但是宽度小于控件的宽度，缩小
         */
        if (drawableHeight > height && drawableWidth < width) {
            scale = height * 1.0f / drawableHeight;
        }

        if ((drawableWidth > width && drawableHeight > height) || (drawableWidth < width && drawableHeight < height)) {
            scale = Math.min(width * 1.0f / drawableWidth, height * 1.0f / drawableHeight);
        }

        /**
         * 得到了初始化时缩放的比例
         */
        this.mInitScale = scale;
        this.mMaxScale = this.mInitScale * 4;
        this.mMidScale = this.mInitScale * 2;

        //将图片移动到当前控件的中心
        int dx = width / 2 - drawableWidth / 2;
        int dy = height / 2 - drawableHeight / 2;

        //this.mScaleMatrix.postTranslate(dx, dy);
        this.mScaleMatrix.setTranslate(dx, dy);
        this.mScaleMatrix.postScale(mInitScale, mInitScale, width / 2, height / 2);

        setImageMatrix(this.mScaleMatrix);
        postInvalidate();
    }


    /**
     * 获取当前图片的缩略值
     *
     * @return
     */
    public float getScale() {
        float[] values = new float[9];
        this.mScaleMatrix.getValues(values);
        return values[Matrix.MSCALE_Y];
    }

    @Override
    public boolean onScale(ScaleGestureDetector detector) {

        if (getDrawable() == null) {
            return true;
        }

        float scale = getScale();
        float scaleFactor = detector.getScaleFactor();

        //缩放范围控制
        if ((scale < mMaxScale && scaleFactor > 1.0f) || (scale > mInitScale && scaleFactor < 1.0f)) {
            if (scale * scaleFactor < mInitScale) {
                scaleFactor = mInitScale / scale;
            }
            if (scale * scaleFactor > mMaxScale) {
                scale = mMaxScale / scale;
            }

            //缩放
            mScaleMatrix.postScale(scaleFactor, scaleFactor, detector.getFocusX(), detector.getFocusY());

            checkBorderAndCenterWhenScale();

            setImageMatrix(mScaleMatrix);
        }

        return true;
    }

    /**
     * 获得图片放大缩小后的宽和高，以及上下左右
     *
     * @return
     */
    private RectF getMatrixRectF() {
        Matrix matrix = mScaleMatrix;
        RectF rectF = new RectF();

        Drawable drawable = getDrawable();

        if (drawable != null) {

            rectF.set(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            matrix.mapRect(rectF);
        }

        return rectF;
    }

    /**
     * 在缩放的时候进行边界控制以及位置控制
     */
    private void checkBorderAndCenterWhenScale() {
        RectF rectF = getMatrixRectF();
        float deltaX = 0;
        float deltaY = 0;

        float width = getWidth();
        float height = getHeight();
        //缩放时， 进行边界检测，防止出现白边
        if (rectF.width() >= width) {
            if (rectF.left > 0) {
                deltaX = -rectF.left;
            }
            if (rectF.right < width) {
                deltaX = width - rectF.right;
            }
        }
        if (rectF.height() >= height) {
            if (rectF.top > 0) {
                deltaY = -rectF.top;
            }
            if (rectF.bottom < height) {
                deltaY = height - rectF.bottom;
            }
        }

        //如果图片的宽度或者高度大于控件的宽或高度，则居中
        if (rectF.width() < width) {
            deltaX = width / 2f - rectF.right + rectF.width() / 2f;
        }
        if (rectF.height() < height) {
            deltaY = height / 2f - rectF.bottom + rectF.height() / 2f;
        }

        mScaleMatrix.postTranslate(deltaX, deltaY);
    }

    @Override
    public boolean onScaleBegin(ScaleGestureDetector detector) {
        return true;
    }

    @Override
    public void onScaleEnd(ScaleGestureDetector detector) {

    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        if (gestureDetector.onTouchEvent(event)) {
            return true;
        }


        this.mScaleGestureDetector.onTouchEvent(event);

        float x = 0;
        float y = 0;

        //拿到多点触控的数量
        int pointerCount = event.getPointerCount();
        for (int i = 0; i < pointerCount; i++) {
            x += event.getX(i);
            y += event.getY(i);
        }
        x /= pointerCount;
        y /= pointerCount;

        if (mLastPointerCount != pointerCount) {
            this.isCanDrag = false;
            this.mLastX = x;
            this.mLastY = y;
        }
        mLastPointerCount = pointerCount;
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                float dx = x - this.mLastX;
                float dy = y - this.mLastY;
                if (!isCanDrag) {
                    isCanDrag = isMoveAction(dx, dy);
                }
                if (isCanDrag) {
                    RectF rectF = getMatrixRectF();
                    if (getDrawable() != null) {
                        //默认可以检查是否流变
                        this.isCheckLeftAndRight = this.isCheckTopAndBottom = true;

                        //如果宽度小于控件宽度，不允许横向移动
                        if (rectF.width() <= getWidth()) {
                            this.isCheckLeftAndRight = false;
                            dx = 0;
                        }
                        //如果高度小于控件高度，不允许纵向移动
                        if (rectF.height() <= getHeight()) {
                            this.isCheckTopAndBottom = false;
                            dy = 0;
                        }

                        mScaleMatrix.postTranslate(dx, dy);

                        checkBorderWhenTranslate();

                        setImageMatrix(mScaleMatrix);
                    }
                    if (rectF.width() > getWidth() || rectF.height() > getHeight()) {
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }
                }

                mLastX = x;
                mLastY = y;
                break;
            case MotionEvent.ACTION_UP:

            case MotionEvent.ACTION_CANCEL:
                mLastPointerCount = 0;
                break;
            default:
                break;
        }


        return true;
    }

    /**
     * 当移动时，进行边界检查
     */
    private void checkBorderWhenTranslate() {

        RectF rectF = getMatrixRectF();
        float deltaX = 0;
        float deltaY = 0;

        int width = getWidth();
        int height = getHeight();
        if (rectF.width() > getWidth() || rectF.height() > getHeight()) {
            getParent().requestDisallowInterceptTouchEvent(true);
        }

        if (rectF.top > 0 && this.isCheckTopAndBottom) {
            deltaY = -rectF.top;
        }
        if (rectF.bottom < height && this.isCheckTopAndBottom) {
            deltaY = height - rectF.bottom;
        }
        if (rectF.left > 0 && this.isCheckLeftAndRight) {
            deltaX = -rectF.left;
        }
        if (rectF.right < width && this.isCheckLeftAndRight) {
            deltaX = width - rectF.right;
        }
        mScaleMatrix.postTranslate(deltaX, deltaY);
    }


    /**
     * 自动放大与缩小
     */
    private class AutoScaleRunnable implements Runnable {

        private final float BIGGER = 1.07f;
        private final float SMALL = 0.93f;

        private float tmpScale = 0;
        /**
         * 缩放的目标值
         */
        private float mTargetScale;
        /**
         * 缩放的中间点
         */
        private float x;
        private float y;

        public AutoScaleRunnable(float mTargetScale, float x, float y) {
            this.mTargetScale = mTargetScale;
            this.x = x;
            this.y = y;

            if (getScale() < mTargetScale) {
                tmpScale = BIGGER;
            }
            if (getScale() > mTargetScale) {
                tmpScale = SMALL;
            }
        }

        @Override
        public void run() {
            //进行缩放
            mScaleMatrix.postScale(tmpScale, tmpScale, x, y);
            checkBorderAndCenterWhenScale();
            setImageMatrix(mScaleMatrix);

            float currentScale = getScale();
            if ((tmpScale > 1.0f) && (currentScale < mTargetScale)
                    || (tmpScale < 1.0f && currentScale > mTargetScale)) {

                postDelayed(this, 16);
            } else {
                float scale = mTargetScale / currentScale;
                mScaleMatrix.postScale(scale, scale, x, y);
                checkBorderAndCenterWhenScale();
                setImageMatrix(mScaleMatrix);

                isAutoScale = false;
            }
        }
    }

    /**
     * 是否发生触发移动
     *
     * @param dx
     * @param dy
     * @return
     */
    private boolean isMoveAction(float dx, float dy) {
        return Math.sqrt(dx * dx + dy * dy) > mTouchSlop;
    }

}
